package presentation;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import dao.*;
import model.*;

/**
 * Servlet implementation class AgregarProductoServlet
 */
@WebServlet("/AgregarProductoServlet")
public class AgregarProductoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public ProductoDAO productoService = null;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AgregarProductoServlet() {
        super();
       
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getSession().setAttribute("MensajeAgregarProducto", null);

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	//	doGet(request, response);
		
		String mensaje = null;

		try{
		
			Integer numero = Integer.parseInt(request.getParameter("inputPrecio"));
			
			Producto proc = new Producto(request.getParameter("inputNombre"), numero, 0,  Integer.parseInt(request.getParameter("inputAdicional")));
			
			this.productoService.save(proc);
			mensaje = "Producto guardado!";
		}
		catch (Exception e){
			mensaje = "Error en los campos..";
			e.printStackTrace();
		}
		
		

		
		request.getSession().setAttribute("MensajeAgregarProducto", mensaje);

		response.sendRedirect("agregarProducto.jsp");
	}
	@Override
	public void init(ServletConfig config) {
		WebApplicationContext context = WebApplicationContextUtils
				.getRequiredWebApplicationContext(config.getServletContext());
		this.productoService = (ProductoDAO) context.getBean(ProductoDAO.class);
	}
}
